package P3;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * 基于线程的Echo客户端/服务器程序设计
 * 3.1基于线程的Echo客户端/服务器程序设计
 * 3.1.2客户端程序（同步）:
 */
public class EchoClient {
    public static void main(String[] args) {
        try {
            // 创建 Socket 实例并连接到服务器
            Socket clientSocket = new Socket("localhost", 8888);
            System.out.println("已连接到服务器");

            // 获取输入/输出流
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));

            // 创建新线程发送数据到服务器
            new Thread(() -> {
                try {
                    // 获取用户输入
                    Scanner scanner = new Scanner(System.in);
                    System.out.print("请输入要发送的消息: ");
                    String message = scanner.nextLine();

                    // 同步方法:发送数据到服务器
                    sendMessage(out, message);
                    System.out.println("已发送数据到服务器: " + message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();

            // 创建新线程接收服务器回显的数据
            new Thread(() -> {
                try {
                    // 同步方法:接收服务器回显的数据
                    String echoMessage = receiveMessage(in);
                    System.out.println("收到服务器回显的数据: " + echoMessage);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static synchronized void sendMessage(BufferedWriter out, String message) throws IOException {
        // 同步方法:发送数据到服务器
        out.write(message + "\n");
        out.flush();
    }

    private static synchronized String receiveMessage(BufferedReader in) throws IOException {
        // 同步方法:接收服务器回显的数据
        return in.readLine();
    }
}